<template>
  <div class="pathPlan">
    <div style="margin-top:15px;">
      <el-form ref="form" label-width="50px">
        <el-autocomplete
          ref="autoSearch"
          v-model="startPointAddress"
          :fetch-suggestions="queryPoi"
          :trigger-on-focus="false"
          class="inline-input"
          placeholder="请输入地址"
          value-key="name"
          clearable
          style="width:87%;"
          @select="handleSelectStartPoint"
        >
          <template slot="prepend">起</template>
        </el-autocomplete>
        <div v-for="throughPointTxt in throughPoints_txt" :key="throughPointTxt.id">
          <el-autocomplete
            ref="autoSearch"
            v-model="throughPointTxt.name"
            :fetch-suggestions="queryPoi"
            :trigger-on-focus="false"
            class="inline-input"
            placeholder="请输入地址"
            value-key="name"
            clearable
            style="width:87%;"
            @select="handleSelectThroughPoint($event,throughPointTxt.id)"
          >
            <template slot="prepend">经</template>
          </el-autocomplete>
          <a
            class="kfb-icon-jianqu addAndRemoveThroughtPoint_txt"
            @click="removeThroughPoint_txt($event,throughPointTxt)"
          />
        </div>

        <el-autocomplete
          ref="autoSearch"
          v-model="endPointAddress"
          :fetch-suggestions="queryPoi"
          :trigger-on-focus="false"
          class="inline-input"
          placeholder="请输入地址"
          value-key="name"
          clearable
          style="width:87%;"
          @select="handleSelectEndPoint"
        >
          <template slot="prepend">终</template>
        </el-autocomplete>
        <span
          v-if="isAddPathPlanPoint"
          class="kfb-icon-tianjia1 addAndRemoveThroughtPoint_txt"
          @click="addThroughPoint_txt"
        />

        <div class="u-pathplanbtn">
          <div style="float:left">
            <el-button type="text" @click="clearPathPlan">清除路线</el-button>
          </div>

          <div style="float:right;margin-right:35px;">
            <el-button type="text" @click="pathPlan">规划</el-button>
          </div>
        </div>
      </el-form>
    </div>

    <!-- 道路规划引导 -->
    <div>
      <el-table
        v-show="routeGuidIsShow"
        :show-header="false"
        :data="tableData"
        height="400px"
        border
        style="width: 100%"
        @row-click="pathGuildHigClick"
        @cell-mouse-enter="pathGuideHigEnter"
        @cell-mouse-leave="pathGuideHigLeave"
      >
        <el-table-column prop="dec" />
      </el-table>
    </div>
    <contextmenu
      :context-menu-data="contextMenuData"
      @selectStartPt="selectStartPt"
      @selectThroughPt="selectThroughPt"
      @selectEndPt="selectEndPt"
    />
  </div>
</template>

<script>
import { Guid } from "@/utils/guid.js";
import { PathPlan } from "@/pages/yzt/components/pathPlan/pathPlan.js";
import contextmenu from "@/pages/yzt/components/pathPlan/contextmenu";
import BoxUtil from "@/assets/js/utils/BoxUtil.js";
import { poiList, poiSearchByLonLat } from "@/api/poi";
import { mapState } from "vuex";
export default {
  components: { contextmenu },
  props: {
    pathPlanHander: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      selectIndex: undefined,
      mapClickPoint: undefined,
      startPointAddress: "", // 起点地址
      endPointAddress: "", // 重点地址
      throughPointAddress: "", // 途经点地址
      throughPoints_txt: [],
      address: [],
      throughPoints_txtCount: -1,
      isAddPathPlanPoint: true,

      // 右键导航
      contextMenuData: {
        // the contextmenu name(1.4.1+ updated)
        menuName: "demo",
        // The coordinates of the display(菜单显示的位置)
        axis: {
          x: null,
          y: null
        },
        // Menu options (菜单选项)
        menulists: [
          {
            fnHandler: "selectStartPt", // Binding events(绑定事件)
            icoName: "static/img/pathPlan/start.png",
            btnName: "设为起点" // The name of the menu option (菜单名称)
          },
          {
            fnHandler: "selectThroughPt", // Binding events(绑定事件)
            icoName: "static/img/pathPlan/through.png",
            btnName: "设为途径点" // The name of the menu option (菜单名称)
          },
          {
            icoName: "static/img/pathPlan/end.png",
            fnHandler: "selectEndPt",
            btnName: "设为终点"
          }
        ]
      },
      tableData: [], // 导航显示内容
      routeGuidIsShow: false, // 导航面板是否显示

      // 导航路径动画效果
      startTime: undefined,
      lineNodes: undefined,
      currentCounter: 0,
      pathPlanLineGeojson: undefined,
      animation: undefined, // 动画回调函数
      duration: 100 // 每一个节点加载时间间隔
    };
  },
  watch: {
    pathPlanHander: async function(nval, oVal) {
      const maps = await this.mapService.getMap();
      if (nval === 4) {
          maps[1].on("contextmenu", e => {
          this.$store.state.eswyzt.mapClickPoint = e.lngLat;
          this.showMenu();
        });
      } else {
        if (
          maps[1].getSource("pathPlanGeojson") !==
          undefined
        ) {
          this.clearPathPlan();
          PathPlan.removePathPlanLayer(maps[1]);
          PathPlan.removePathPlanGuidLayer(maps[1]);
        }
      }
    }
  },
  mounted() {},
  methods: {
    // 显示右键菜单
    showMenu() {
      event.preventDefault();
      var x = event.clientX;
      var y = event.clientY;
      // Get the current location
      this.contextMenuData.axis = {
        x,
        y
      };
    },

    // 选择起点
    selectStartPt() {
      if (this.$store.state.eswyzt.mapClickPoint) {
        PathPlan.setStartPoint(
          this.$store.state.eswyzt.mapClickPoint.lng,
          this.$store.state.eswyzt.mapClickPoint.lat,
          this.$store.state.eswyzt.map
        );
        // this.poiSearchByLonLat(this.$store.state.eswyzt.mapClickPoint.lng, this.$store.state.eswyzt.mapClickPoint.lat, 100).then(poiData => {
        //   if (poiData && poiData.length > 0) {
        //     this.startPointAddress = poiData[0].name
        //   } else {
        //     this.startPointAddress = this.$store.state.eswyzt.mapClickPoint.lng.toFixed(4) + ',' + this.$store.state.eswyzt.mapClickPoint.lat.toFixed(4)
        //   }
        // })
      }
    },

    // 选择途径点
    selectThroughPt() {
      if (this.$store.state.eswyzt.mapClickPoint) {
        PathPlan.setPathPlanPoint(
          this.$store.state.eswyzt.map,
          this.$store.state.eswyzt.mapClickPoint.lng,
          this.$store.state.eswyzt.mapClickPoint.lat
        );
      }
    },

    // 选择终点
    selectEndPt() {
      if (this.$store.state.eswyzt.mapClickPoint) {
        PathPlan.setEndPoint(
          this.$store.state.eswyzt.mapClickPoint.lng,
          this.$store.state.eswyzt.mapClickPoint.lat,
          this.$store.state.eswyzt.map
        );
        // this.poiSearchByLonLat(this.$store.state.eswyzt.mapClickPoint.lng, this.$store.state.eswyzt.mapClickPoint.lat, 100).then(poiData => {
        //   console.log(poiData)
        //   if (poiData && poiData.length > 0) {
        //     this.endPointAddress = poiData[0].name
        //   } else {
        //     this.endPointAddress = this.$store.state.eswyzt.mapClickPoint.lng.toFixed(4) + ',' + this.$store.state.eswyzt.mapClickPoint.lat.toFixed(4)
        //   }
        // })
      }
    },

    // 路径规划查询
    pathPlan() {
      PathPlan.addPathPlanLayer(this.$store.state.eswyzt.map);
      this.pathPlanLineGeojson = {
        type: "FeatureCollection",
        features: [
          {
            type: "Feature",
            geometry: {
              type: "LineString",
              coordinates: []
            }
          }
        ]
      };

      PathPlan.pathPlan()
        .then(pathResult => {
          this.$store.state.eswyzt.map.fitBounds(
            BoxUtil.getFeatureBounds(
              pathResult.result.pathList[0].edgeFeatures
            ),
            { padding: { top: 300, bottom: 300, left: 450, right: 300 } }
          );

          // 动画效果
          this.lineNodes =
            pathResult.result.pathList[0].route.geometry.coordinates[0];
          this.startTime = performance.now();
          (this.currentCounter = 0), this.animateLine();

          // 导航
          const pathGuildItems =
            pathResult.result.pathList[0].pathGuideItems.features;
          this.tableData = this.formatGuidItems(pathGuildItems);
          this.routeGuidIsShow = true;
        })
        .catch(err => {
          this.$message.error(err);
        });
    },

    // 路径规划高亮
    pathGuideHigEnter($event) {
      PathPlan.addPathPlanGuidLayer(this.$store.state.eswyzt.map);
      const pathPlanGuidLineGeojson = {
        type: "FeatureCollection",
        features: [
          {
            type: "Feature",
            geometry: {
              type: "LineString",
              coordinates: []
            }
          }
        ]
      };
      pathPlanGuidLineGeojson.features[0].geometry = $event.geo;
      this.$store.state.eswyzt.map
        .getSource("pathPlanGuildGeojson")
        .setData(pathPlanGuidLineGeojson);
    },

    // 路径规划离开不高量
    pathGuideHigLeave($event) {
      const pathPlanGuidLineGeojson = {
        type: "FeatureCollection",
        features: [
          {
            type: "Feature",
            geometry: {
              type: "LineString",
              coordinates: []
            }
          }
        ]
      };
      if (
        this.$store.state.eswyzt.map.getSource("pathPlanGuildGeojson") !==
        undefined
      ) {
        this.$store.state.eswyzt.map
          .getSource("pathPlanGuildGeojson")
          .setData(pathPlanGuidLineGeojson);
      }
    },

    // 定位到导航路段位置
    pathGuildHigClick($event) {
      if (($event.geo.type = "LineString")) {
        this.$store.state.eswyzt.map.fitBounds(
          BoxUtil.getFeatureBounds($event.geo),
          { padding: { top: 300, bottom: 300, left: 450, right: 300 } }
        );
      }
    },
    // 路径规划线路动态效果循环回调函数
    animateLine(timestamp) {
      const time = performance.now();
      if (this.currentCounter < this.lineNodes.length) {
        if (this.duration < time - this.startTime) {
          if (
            this.$store.state.eswyzt.map.getLayer("pathPlan-lines") !==
            undefined
          ) {
            this.pathPlanLineGeojson.features[0].geometry.coordinates.push(
              this.lineNodes[this.currentCounter]
            );
            this.$store.state.eswyzt.map
              .getSource("pathPlanGeojson")
              .setData(this.pathPlanLineGeojson);
            this.currentCounter = this.currentCounter + 1;
            this.startTime = time;
          }
        }
        this.animation = requestAnimationFrame(this.animateLine);
      } else {
        cancelAnimationFrame(this.animation);
      }
    },

    // 格式化GuidItems
    formatGuidItems(pathGuildItems) {
      const pathGuildFormatItems = [];
      for (let i = 0; i < pathGuildItems.length; i++) {
        let pathGuildFormatItem = {};
        if (i === pathGuildItems.length - 1) {
          pathGuildFormatItem = { dec: "到达终点" };
        } else {
          const pathGuidItem = pathGuildItems[i].properties;
          if (pathGuidItem.description.indexOf("路由点") > -1) {
            pathGuildFormatItem = { dec: "到达途径点" };
          } else {
            const value = pathGuidItem.description.replace(/[^\d.]/g, "");
            let value10 = "";
            if (value) {
              let formatLen = parseFloat(value);
              if (formatLen >= 1000) {
                formatLen = parseFloat(value) / 1000;
                value10 = pathGuidItem.description.replace(
                  value + "米",
                  formatLen.toFixed(2) + "千米"
                );
              } else {
                value10 = pathGuidItem.description.replace(
                  value,
                  formatLen.toFixed(2)
                );
              }
              pathGuildFormatItem = { dec: value10 };
            } else {
              pathGuildFormatItem = {
                dec: pathGuidItem.description.replace("路由点", "途经点")
              };
              console.log(pathGuidItem.description);
            }
          }
        }
        this.$set(pathGuildFormatItem, "geo", pathGuildItems[i].geometry);
        this.$set(
          pathGuildFormatItem,
          "bound",
          pathGuildItems[i].properties.bounds
        );
        pathGuildFormatItems.push(pathGuildFormatItem);
      }

      return pathGuildFormatItems;
    },

    // 清除规划
    clearPathPlan() {
      PathPlan.clearPathPlan(this.$store.state.eswyzt.map);
      this.tableData = [];
      this.routeGuidIsShow = false;
      this.startPointAddress = undefined;
      this.endPointAddress = undefined;
    },

    // 查询POI数据
    queryPoi(queryString, cb) {
      poiList({
        keyWord: queryString,
        limit: 10
      }).then(res => {
        const total = res.data.count;
        const poiData = res.data.data;
        cb(poiData);
        if (this.total == 0) {
          this.$message({
            type: "info",
            message: "没有数据!"
          });
        }
      });
    },

    // poi选择起点
    handleSelectStartPoint(item) {
      PathPlan.setStartPoint(
        item.gpsx,
        item.gpsy,
        this.$store.state.eswyzt.map
      );
      this.$store.state.eswyzt.map.flyTo({
        center: [item.gpsx, item.gpsy],
        zoom: 15
      });
    },

    // poi选择途经点
    handleSelectThroughPoint(item, id) {},

    // poi选择终点
    handleSelectEndPoint(item) {
      PathPlan.setEndPoint(item.gpsx, item.gpsy, this.$store.state.eswyzt.map);
      this.$store.state.eswyzt.map.flyTo({
        center: [item.gpsx, item.gpsy],
        zoom: 15
      });
    },
    addThroughPoint_txt() {},
    removeThroughPoint_txt($event, throughPointTxt) {},

    // 通过点位设置POI
    poiSearchByLonLat(lng, lat, maxDistance) {
      return new Promise((resolve, reject) => {
        poiSearchByLonLat({
          point: [lng, lat],
          maxDistance: maxDistance,
          limit: 10
        }).then(res => {
          resolve(res.data);
        });
      });
    }
  },
  computed: {
    ...mapState({

      // 地图模块控件
      mapModuleIndex(state) {
        return state.eswyzt.mapModuleIndex;
      },

      mapService(state) {
        return state.eswyzt.mapService;
      },
      maps(state){
        return state.eswyzt.getMap();
      }
    })
  }
};
</script>

<style>
.pathPlan {
  position: relative;
  height: 100%;
  z-index: 999;
  margin-top: -10px;
}

.pathPlan .divisionDiv {
  height: 30px;
}

.pathPlan .divisionDiv > svg {
  height: 100%;
  float: right;
}

.el-collapse-item {
  width: 100%;
}

.el-collapse-item__content {
  padding-bottom: 0px;
}

.list-group-item {
  border: 0px;
  padding-bottom: 2px;
  padding: 0.7rem 0.5rem;
}

.bg-purple {
  background: white;
}

.bg-purple-light {
  background: white;
}

.pathPlan .grid-content {
  border-radius: 0px;
  /* min-height: 35px; */
  height: 40px;
}

.pathPlan .grid-content:hover {
  cursor: pointer;
}

.pathPlan .grid-content svg {
  width: 38px;
  height: 48px;
  margin-left: 15px;
  margin-top: 6px;
  margin-bottom: 6px;
  margin-right: 10px;
  vertical-align: middle;
}

.pathPlan .el-input__inner {
  border-radius: 0px;
  width: 100%;
}

.pathPlan .el-form-item {
  margin-bottom: 0px;
}

.pathPlan .u-pathplanbtn {
  margin-left: 20px;
  /*margin-top: 5px;*/
}

.pathPlan .el-button--text {
  padding-top: 5px;
}

.pathPlan .el-input-group__append,
.el-input-group__prepend {
  padding: 0 8px;
  border-radius: 0px;
}

.pathPlan .el-input-group {
  margin-bottom: 7px;
}

.pathPlan .addAndRemoveThroughtPoint_txt {
  display: inline-block;
  width: 20px;
  height: 20px;
  margin-left: 8px;
  color: #409eff;
  cursor: pointer;
}

.pathPlan .el-button {
  /* background: #1685d9;
    padding: 8px 20px; */
  color: #409eff;
}

.pathPlan form {
  margin-left: 3px;
}

.pathPlan .el-input__inner {
  height: 34px;
  line-height: 34px;
  font-size: 12px;
  font-family: "Arial";
}

.pathPlan .el-input {
  margin-left: 10px;
}

.pathPlan .el-table td,
.el-table th {
  padding: 7px 10px;
}

.pathPlan .el-table {
  font-size: 12px;
  font-family: Arial, Helvetica, SimSun, sans-serif;
}
</style>

